package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class LessonChangeListener {

    private final ILearningLessonService LessonService;

    //1. 监听订单支付消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "learning.lesson.pay.queue", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC) ,
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void listenLessonPay(OrderBasicDTO order){ //从消息队列中监听
        // 1.判断订单是否是课程订单
        if (order==null||
                order.getOrderId()==null||
                order.getUserId()==null||
                CollUtils.isEmpty(order.getCourseIds())) {
            log.error("订单信息有误，order:{}",order);
            return;
        }
        //2.订单状态正常,就将课程添加到课表中
        log.debug("监听到用户{}的订单{}，需要添加课程{}到课表中",
                order.getUserId(), order.getOrderId(), order.getCourseIds());
        LessonService.addLesson(order);
    }

    //2. 监听订单退款消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "learning.lesson.refund.queue", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC) ,
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void ListenDelete(OrderBasicDTO order){
        //1.判断订单是否是课程订单
        if (order==null||
                order.getOrderId()==null||
                order.getUserId()==null||
                CollUtils.isEmpty(order.getCourseIds())) {
            log.error("订单信息有误，order:{}",order);
            return;
        }
        //2. 订单状态正常,就从课表中删除相应课程
        LessonService.removeLesson(order);
    }
}
